package com.example.custsecurity.security.servic;

import cn.hutool.crypto.digest.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class CustUserDetailsServic implements UserDetailsService {

//    username 参数：前端输入的用户名  用户名必须在数据库是唯一的
//    loadUserByUsername：根据输入的用户名去数据库或持久化空间查找对应用户的相关信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.debug(".....用户名"+username);
        /*
        * 调用Mapper接口
        *
        * 模拟数据库匹配
        * 业务：任何用户 统一密码
        * */
        return queryUserByName(username);
    }

    //    模拟数据库查询方法
    private User queryUserByName(String username){
        //        模拟所有的用户密码都是123并进行MD5加密
        String db_password = MD5.create().digestHex16("123");

        if ("admin".equalsIgnoreCase(username)){

            //        模拟创建对应用户的权限集合
            List<SimpleGrantedAuthority> list =new ArrayList<>();
            list.add(new SimpleGrantedAuthority("ADMIN"));
            list.add(new SimpleGrantedAuthority("SYS"));
            //        该对象模拟的是从数据库查询出来的用户信息
            User db_user = new User(username,db_password,list);
            return db_user;
        }else if ("sys".equalsIgnoreCase(username)){

            List<SimpleGrantedAuthority> list =new ArrayList<>();
            list.add(new SimpleGrantedAuthority("SYS"));
            User db_user = new User(username,db_password,list);
            return db_user;

        }else {
            List<SimpleGrantedAuthority> list =new ArrayList<>();
            list.add(new SimpleGrantedAuthority("ANONYMOUS"));
            User db_user = new User(username,db_password,list);
            return db_user;
        }
    }
}
